package com.jingdianjichi.club.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jingdianjichi.club.gateway.entity.AuthPermission;
import com.jingdianjichi.club.gateway.entity.AuthRole;
import com.jingdianjichi.club.gateway.redis.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 自定义权限验证接口扩展 
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisUtil redisUtil;

    private String authPermissonPrefix = "auth.permisson";

    private String authRolePrefix = "auth.role";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuth(loginId.toString(), authPermissonPrefix);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {

        return getAuth(loginId.toString(), authRolePrefix);
    }

    private List<String> getAuth(String loginId, String prefix) {
        String s = redisUtil.buildKey(prefix, loginId.toString());
        String s1 = redisUtil.get(s);
        if (StringUtils.isEmpty(s1)) {
            return Collections.emptyList();
        }
        List<String> authList = new ArrayList<>();
        if (authRolePrefix.equals(prefix)) {
            List<AuthRole> authRoleList = new Gson().fromJson(s1, new TypeToken<List<AuthRole>>() {
                    }.getType()
            );
            for (AuthRole authRole : authRoleList) {
                authList.add(authRole.getRoleKey());
            }
        } else if (authPermissonPrefix.equals(prefix)) {
            List<AuthPermission> authPermissionList = new Gson().fromJson(s1, new TypeToken<List<AuthPermission>>() {
                    }.getType()
            );
            for (AuthPermission authPermission : authPermissionList) {
                authList.add(authPermission.getPermissionKey());
            }
        }
        return authList;
    }
}
